package models

import (
	"context"
	"gameserver/tools/TestRobot/cmd"
	"gameserver/tools/TestRobot/internal"
	"sync"
	"time"

	"gitee.com/night-tc/gobige/common"
	"gitee.com/night-tc/gobige/logger"
)

// RobotMgr 机器人管理器，负责管理所有机器人用户及其状态
type RobotMgr struct {
	userli map[uint64]*RobotUser // 用户列表

	msgcmdch  chan *cmd.InputCmd // 指令通道
	userch    chan *RobotUser    // 用户通道
	caluserch chan uint64        // 用户ID通道

	/* 机器人测试状态信息 */
	noteli     map[string]int    // 状态统计
	userNoteLi map[uint64]string // 用户状态
	notelock   sync.RWMutex      // 状态锁
}

// newRobotMgr 创建新的机器人管理器
func newRobotMgr() *RobotMgr {
	mgr := new(RobotMgr)
	mgr.userli = make(map[uint64]*RobotUser)
	mgr.noteli = make(map[string]int)
	mgr.userNoteLi = make(map[uint64]string)

	mgr.msgcmdch = make(chan *cmd.InputCmd, 1)
	mgr.userch = make(chan *RobotUser, 10)
	mgr.caluserch = make(chan uint64, 10)
	return mgr
}

// SetUser 添加用户到管理器
func (this *RobotMgr) SetUser(user *RobotUser) {
	this.userch <- user
}

// 添加指令
func (this *RobotMgr) AddCmd(inputcmd *cmd.InputCmd) {
	this.msgcmdch <- inputcmd
}

// SetNoteStatus 设置用户状态，并维护状态统计
func (this *RobotMgr) SetNoteStatus(pid uint64, note string) {
	this.notelock.Lock()
	defer this.notelock.Unlock()
	if old, ok := this.userNoteLi[pid]; ok {
		this.noteli[old]--
	}
	if note == "" {
		//表示退出用户
		delete(this.userNoteLi, pid)
		logger.Infof("SetNoteStatus pid:%d 退出", pid)
	} else {
		this.userNoteLi[pid] = note
		this.noteli[note]++
		logger.Infof("SetNoteStatus pid:%d note:%s", pid, note)
	}

}
func (this *RobotMgr) hander(ctx context.Context) {
	tk := time.NewTicker(time.Minute)
	defer tk.Stop()
	sb := common.NewStringBuilder()
	for {
		select {
		case <-ctx.Done():
			{
				if this.PlayerNum() == 0 {
					return
				}
			}
		case inputcmd := <-this.msgcmdch:
			if inputcmd.Cmd.Runf != nil {
				internal.Thgo.Go(func(ctx context.Context) {
					inputcmd.Cmd.Runf(inputcmd)
				})
			} else {
				for _, user := range this.userli {
					user.Input.Store(inputcmd)
				}
			}
		case user := <-this.userch:
			this.userli[user.UserID] = user
		case id := <-this.caluserch:
			delete(this.userli, id)
		case <-tk.C:
			this.Status(sb)
			logger.Info(sb.ToString())
		}
	}
}

// Status 输出当前机器人状态统计到字符串构建器
func (this *RobotMgr) Status(sb *common.StringBuilder) {
	sb.Clear()
	this.notelock.RLock()
	defer this.notelock.RUnlock()
	sb.Append("机器人进度：")
	sb.AppendInt(len(this.userNoteLi))
	sb.Append(" ")
	for k, v := range this.noteli {
		if v == 0 {
			continue
		}
		sb.Append(k)
		sb.Append(":")
		sb.AppendInt(v)
		sb.Append(" ")
	}
}

// PlayerNum 获取当前活跃机器人数量
func (this *RobotMgr) PlayerNum() int {
	this.notelock.RLock()
	defer this.notelock.RUnlock()
	return len(this.userNoteLi)
}
